package com.yexx.nacos.config.security;

import com.yexx.core.entity.ApiResponse;
import com.yexx.starter.security.basic.SecurityUserDetailsService;
import com.yexx.user.api.AccountApi;
import com.yexx.user.api.UserApi;
import com.yexx.user.request.account.AccountSimpleRequest;
import com.yexx.user.domain.Account;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Collections;

/**
 * Description: 系统用户服务
 *
 * @author: zuomin (myleszelic@outlook.com)
 * @date: 2020/11/03-09:53
 */
@Slf4j
@Component
public class SysUserDetailsService implements SecurityUserDetailsService {

    @Autowired
    private UserApi userApi;

    @Autowired
    private AccountApi accountApi;

    @Override
    public void loginSuccessful(HttpServletRequest request, HttpServletResponse response, Authentication authResult) {
        log.info("login success");
    }

    @Override
    public Boolean checkBindDevice(String phoneNumber, String deviceUuid) {
        //登陆无需绑定设备
        return true;
    }

    @Override
    public Boolean bindDevice(String phoneNumber, String deviceUuid, String osName, String osVersion) {
        return true;
    }

    @Override
    public UserDetails loadUserByUsername(String phoneNumber) throws UsernameNotFoundException {
        AccountSimpleRequest simpleRequest = new AccountSimpleRequest();
        simpleRequest.setUsername(phoneNumber);
        ApiResponse<Account> one = accountApi.findOne(simpleRequest);
        if (one.getCode().equals(10000) && one.getData() != null) {
            Account account = one.getData();
            SysUserContext userContext = new SysUserContext(account.getId(), account.getUsername(), account.getSecret(), buildAuthorities());

            userContext.setName(account.getName());
            userContext.setAvatarUrl(account.getAvatarUrl());
            userContext.setEmail(account.getEmail());
            userContext.setGender(account.getGender());
            userContext.setIdCardNo(account.getIdCardNo());
            userContext.setRegisterTime(account.getRegisterTime());
            userContext.setDisable(account.getDisable());
            userContext.setPwdStatus(account.getPwdStatus());
            return userContext;
        }
        return null;
    }

    private Collection<? extends GrantedAuthority> buildAuthorities() {
        return Collections.emptySet();
    }
}
